import XLSX from 'xlsx';
import { message, Modal } from 'antd';
import * as  ConstPage from './const';

const confirm = Modal.confirm;

/*
*   处理后端返回数据，返回Anted树组件可以识别的数据，针对嵌套架构
*   data:权限数据,嵌套
*   treeMap: key-value对象 key:权限数据对应的id,value:树结构中key值
*   treeData:转换的树结构数据
*   parentid:根节点id
*/
export const getTreeDataForNesting = (data,treeMap = [],treeData = [],parentid = 0) => {
    data.map(item => {
        treeData.push({
            title:item.name,
            key:parentid + '-' + item.id,
            id:item.id,
            value:item.id,
            type:item.type,
            permission:item.permission,
            children:[]
        });
        treeMap[item.id] = parentid + '-' + item.id;
        item.subPermissionList && item.subPermissionList.length ? getTreeDataForNesting(item.subPermissionList,treeMap,treeData[treeData.length-1].children,treeData[treeData.length-1].key):null;
        });
    return treeData;
}

/*
*   处理后端返回数据，返回Anted树组件可以识别的数据，针对平行结构
*/
export const getTreeDataForParallel = (data,treeData = [],parentId = 0,parentNode = undefined) => {
    data.map(item => {
        if(parentId == item.parentid){
            treeData.push({
                title:item.name,
                key:!parentNode ? parentId + '-' + item.id : parentNode.key + '-' + item.id ,
                id:item.id,
                permission:item.permission,
                type:item.type,
                children:[]
            });
            getTreeDataForParallel(data,treeData[treeData.length-1].children,item.id,treeData[treeData.length-1]);
        }
    });
    return treeData;
}

/*
获取所有需要勾选的Keys
treeMap: key-value对象 key:权限数据对应的id,value:树结构中key值
current : 当前所有权限,数组
checkedKeys:勾选的key值,数组
*/
export const getTreeDataKeys = (treeMap,current) => {
    const checked = [],halfChecked = [];
    const ids = current.map(item => item.parentid);
    current.map(item => {
        if(treeMap[item.id] && contains(treeMap,item.id) && !ids.includes(item.id)){
            checked.push(treeMap[item.id]);
        }else{
            halfChecked.push(treeMap[item.id]);
        }
    });
    return {checked,halfChecked};
};

const contains = (treeMap,id) =>{
    const value = treeMap[id];
    const valus = Object.values(treeMap);
    for(let i=0;i<valus.length;i++){
        if(value != valus[i] && valus[i].indexOf(value)!==-1){
            return false;
        }
    }
    return true;
}

export const getExpandKeys = (checkedKeys,expandedKeys = []) => {
    checkedKeys.map(item => {
        if(!item || typeof item !== 'string') return;
        if(!expandedKeys.includes(item)){
            expandedKeys.push(item);
        }
        let splitArray = item.split('-');
        let key = item;
        while(splitArray.length > 2){
             key = key.substring(0,key.lastIndexOf('-'));
            if(!expandedKeys.includes(key)){
                expandedKeys.push(key);
            }
            splitArray = key.split('-');
        }

    });
    return expandedKeys;
}

export const getPermissionIds = (permissionList,ids=[]) => {
    permissionList.map(item => {
        ids.push(item.id);
    });
    return ids;
}



export const validateStartIp = (rule,value,callback,endIp) => {
    if(!value || !value.length) {callback(); return;}
    if(!checkIP(value)){
        callback('开始IP格式不正确');
        return;
    }
    const sysCompany = localStorage.getItem('user')?JSON.parse(localStorage.getItem('user')).sysCompany:{};//当前人所在分部信息
    if(compareIP(sysCompany.startIp,value) == 1){
        callback('开始IP不能小于当前分部开始IP');
        return;
    }
    if(endIp && compareIP(value,endIp) == 1){
        callback('开始IP不能大于结束IP');
    }else{
        callback();
    }
}
export const validateEndIp = (rule,value,callback,startIp) => {
    if(!value || !value.length) {callback(); return;}
    if(!checkIP(value)){
        callback('结束IP格式不正确');
        return;
    }
    const sysCompany = JSON.parse(localStorage.getItem('user')).sysCompany;//当前人所在分部信息
    if(compareIP(sysCompany.endIp,value) == -1){
        callback('结束IP不能大于当前分部结束IP');
        return;
    }
    if(startIp && compareIP(startIp,value) == 1){
        callback('结束IP不能小于开始IP');
    }else{
        callback();
    }
}
export const compareIP = (startIp, endId) =>
{
    let startIpArr = [],endIpArr = [];
    startIpArr = startIp.split(".");
    endIpArr = endId.split(".");
    for (var i = 0; i < 4; i++)
    {
        if (Number(startIpArr[i])>Number(endIpArr[i]))
        {
            return 1;
        }
        else if (Number(startIpArr[i])<Number(endIpArr[i]))
        {
            return -1;
        }
    }
    return 0;
}

export const checkIP = (value) =>{
    const reg = /^(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])$/;
    return reg.test(value);
}

/**
 *
 * @param {*表头} _headers
 * @param {*表格数据} _data
 * @param {*导出文件名} title
 */
export const outPutExcel = (_headers, _data, title, maxData) => {
    if(_data.length==0){
        message.error('暂无需要导出的表格数据');
        return ;
    }
    // if(maxData!=undefined&&parseInt(maxData)<=0){
    //     message.info('表格数据为空')
    //     return ;
    // }else{
    var headers = _headers
    .map((v, i) => Object.assign({}, { v: v, position: String.fromCharCode(65 + i) + 1 }))
    .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v } }), {});

    var data = _data
        .map((v, i) => _headers.map((k, j) => Object.assign({}, { v: v[k], position: String.fromCharCode(65 + j) + (i + 2) })))
        .reduce((prev, next) => prev.concat(next))
        .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v } }), {});

    // 合并 headers 和 data
    var output = Object.assign({}, headers, data);
    // 获取所有单元格的位置
    var outputPos = Object.keys(output);
    // 计算出范围
    var ref = outputPos[0] + ':' + outputPos[outputPos.length - 1];

    // 构建 workbook 对象
    var wb = {
        SheetNames: ['mySheet'],
        Sheets: {
            'mySheet': Object.assign({}, output, { '!ref': ref })
        }
    };
    // 导出 Excel
    return XLSX.writeFile(wb, title + '.xlsx');
    // }
}

//校验IP范围的正确性
export const checkIPValue = (value, startIp, endIp) =>{
    if(startIp!=''){
        startIp = startIp.split(".");
        endIp = endIp.split(".");
        let IPValue = value.split(".");
        for(let i=0; i < startIp.length; i++){
            let s = parseInt(startIp[i]);
            let c = parseInt(IPValue[i]);
            let e = parseInt(endIp[i]);
            if(!(s<=c&&c<=e)){
                return false;
            }
        }
        return true
    }

    return true;
}

//校验IP段的大小
export const checkIPCount = (startIp, endIp) =>{
    startIp = startIp.split(".");
    endIp = endIp.split(".");
    for(let i=0; i < startIp.length; i++) {
        let s = parseInt(startIp[i]);
        let e = parseInt(endIp[i]);
        if (s > e) {
            return false;
        } else {
            return true;
        }
    }
}

export const filter = (prefix, value) => {
    const excludes = ['start','end'];
    if(value){
        if(typeof value == 'string' && !excludes.includes(prefix)){
            value = value.replace(/ /g,'');
        }
        return value;
    }
}

export const getPageParams = (pagination,isDelete = false) => {
    const params = {
        page: pagination.current -1 ,//后台分页默认从第0页开始
        size: pagination.pageSize || 10,
    };
    //若当前页只有一条数据,并且不是第一页,删除后,展示前一页的数据
    if(isDelete && pagination.current == Math.ceil(pagination.total/pagination.defaultPageSize)
        && pagination.total%pagination.defaultPageSize == 1){
        params.page > 0 && params.page --;
    }
    return params;
}

//数据统计序列号校验方法
export const CheckSnFunc = (value) =>{
    const pattern = /^([a-z|A-Z|0-9|.!@$*-=+|]{0,250})$/
    if(value!=null&&value!=""&&!value.match(pattern)){
        return true
    }
    return false
}

//html转义方法
export const HTMLDecode = (text) =>{
    if(text!=undefined&&text!=''&&text.indexOf('&lt;')>=0){
        let temp = document.createElement('span')
        temp.innerHTML = text; 
        let output = temp.innerText || temp.textContent; 
        temp = null; 
        return output;
    }
    return text;
}

//html反转义方法
export const HTMLEncode = (html) =>{
    if(html!=undefined&&html!=''&&html.indexOf('&lt;')<0){
        let temp = document.createElement('div');
        (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
        let output = temp.innerHTML; 
        temp = null; 
        return output;
    }
    return html
}

//获取y轴数据最大值
export const GetMaxValue = (array) =>{
    let max = Math.max(...array);
    /*let maxValue = max*0.1;*/
    if(max<5){
        return max+2;
    }else{
        /*return maxValue<10?(parseInt(maxValue)+1)*10:(parseInt(maxValue*1.2))*10;*/
        return maxValueFun(max);
    }
}
const maxValueFun = (maxValue,array = [5]) => {
    let quotient = Math.floor(maxValue/5);
    if(maxValue%5 == 0 && quotient < 5){
        return (quotient + 1)*5;
    }
    let result = maxValue;
    const length = (result+'').length;
    const interval = Math.pow(10,length-1);
    const res = Math.ceil(result/interval);
    if(res <= 5){
        result = 5 * interval;
    }else if(res <= 5*1.5 && interval !== 1){
        result = 5 * interval * 1.5;
    }else{
        result = 5 * interval * 2;
    }
    return result;
}
//计算图表y轴分割段数
export const GetInterval = (maxValue) =>{
    if(maxValue < 7){
        return 1;
    }else if(maxValue < 26){
        return 5;
    }
    return maxValue/5;
}
export const objectIsNull = (object) => {
    if(typeof object == 'object'){
        return Boolean(Object.keys(object).length);
    }else{
        return false;
    }
}

export const shallowEqual = (objA, objB) => {
    if(objA == objB) {
        return true;
    }
    var keyA = Object.keys(objA),
        keyB = Object.keys(objB);

    if(keyA.length != keyB.length) {
        return false;
    }

    for(var idx = 0, len = keyA.length; idx < len; idx++ ) {
        var key = keyA[idx];

        if(!objB.hasOwnProperty(key)) {
            return false;
        }
        var valueA = objA[key],
            valueB = objB[key];
        // 无差别比较，引用类型比较引用，基础类型直接比较值
        if(valueA !== valueB) {
            return false;
        }
    }
    return true;
}

/**
 * 下载返回的excel值
 * @param {*二进制对象} blob 
 * @param {*文件名} fileName 
 */
export const downloadExcel = (blob, fileName, data) =>{
    if(data.type=='application/json'){
        let fr = new FileReader();
        fr.readAsText(data);
        let obj = {};
        fr.onload = function(evt) {
            var result = evt.target.result;
            obj = JSON.parse(result);
            if(obj.code=='400'){
                message.error(obj.msg);
                return ;
            }
            if(obj.code=='404.1'){
                message.error(obj.msg);
                return ;
            }
        };
        return ;
    }
    if (window.navigator.msSaveOrOpenBlob) {
        // if browser is IE
        navigator.msSaveBlob(blob, fileName);//filename文件名包括扩展名，下载路径为浏览器默认路径
    } else {
        var url = window.URL.createObjectURL(blob);   // 获取 blob 本地文件连接 (blob 为纯二进制对象，不能够直接保存到磁盘上)
        var a = document.createElement('a');
        a.href = url;
        a.download = decodeURIComponent(fileName);
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    }
}

export const distinctArray = (array,distinct = []) => {
    for(let i=0;i<array.length;i++){
        if(!distinct.includes(array[i])){
            distinct.push(array[i]);
        }
    }
    return distinct;
}

export const getButtonCol = (permission) => {
    const user = JSON.parse(localStorage.getItem('user'));
    const permissions = user ? user.permission : [];
    if (permissions.includes(permission)) {
        return ConstPage.BUTTONLAYOUT;
    } else {
        return { xs: 0};
    }
}

export const getCheckCol = (permission) => {
    const user = JSON.parse(localStorage.getItem('user'));
    const permissions = user ? user.permission : [];
    if (permissions.includes(permission)) {
        return {
            xs: 24,
            sm: {span: 24},
            md: {span: 5, offset: 6},
            lg: {span: 3, offset: 14}
        };
    } else {
        return {
            xs: 24,
            sm: {span: 24},
            md: {span: 5, offset: 10},
            lg: {span: 4, offset: 16},
            xl: {span: 3, offset: 18},
        };
    }
}